#include "../head.h"

/*图片展示模块*/

int show_bmp( int x0, int y0, const char *filename)
{
    //1.打开图片
    int fd = open( filename, O_RDWR );
    if( fd == -1 )
    {
        perror("OPEN ERROR");
    }
    //2.读取数据
    //读取宽、高、色深
    //读取像素点的数据
    int width = 0, height = 0;
    int depth = 0;
    if(lseek( fd, 0x12, SEEK_SET) == -1 ||read( fd, &width, 4) != 4 || lseek(fd, 0x16, SEEK_SET) == -1 ||read( fd, &height, 4) != 4 || lseek(fd, 0x1c, SEEK_SET) == -1 ||read( fd, &depth, 4) != 4)
    {
        perror( "Read ERROR" );
        return -1;
    }

    int laizi = 0;      //表示要填充的字节数
    int line_size = 0;  //实际的字节数

    laizi = 4 - (abs(width)*(depth/8))%4 ;
    if( laizi == 4 )
    {
        laizi = 0;
    }

    //实际的字节数 = 有效字节数 + 赖子
    line_size = abs(width)*(depth/8) + laizi ;

    //一口气把所有像素点数据全部读取出来
    unsigned char buf[ abs(height) * line_size ];
    if(lseek( fd, 0x36, SEEK_SET ) == -1 || read( fd, buf, abs(height) * line_size ) != abs(height) * line_size){
        perror(" Read(1) ERROR");
        close(fd);
    }

    //3.显示
    int color;
    unsigned b,g,r,a=0;
    int i,j;
    int num = 0;

    for( j=0; j<abs(height); j++ )
    {
        for( i=0; i<abs(width); i++ )
        {
            //合成颜色数据
            b = buf[num++];
            g = buf[num++];
            r = buf[num++];
            if( depth == 32 )
            {
                a = buf[num++];
            }
            color = (a<<24) | (r<<16) | (g<<8) | b;

            //画点
            display_point( (width>0 ? i : abs(width)-1-i)+x0,
                           (height>0 ? abs(height)-1-j : j)+y0,
                           color );
        }

        num = num + laizi;  //跳过无效的数据

    }
    //4.关闭图片
    close(fd);
    return 0;
}
